package me.mingshan.leetcode;

/**
 *https://leetcode.cn/problems/remove-linked-list-elements/
 *
 * @author hanjuntao
 * @date 2025/7/8 0008
 */
public class L_203_remove_linked_list_elements {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return "val:" + val;
        }
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(6);
        l1.next.next.next = new ListNode(3);
        l1.next.next.next.next = new ListNode(4);
        l1.next.next.next.next.next = new ListNode(5);
        l1.next.next.next.next.next.next = new ListNode(6);

        System.out.println(removeElements(l1, 6));
    }


    public static ListNode removeElements(ListNode head, int val) {
        ListNode curr = head;
        ListNode prev = null;

        while (curr != null) {
            if (curr.val == val) {
                // 当前节点的下一个节点
                ListNode next = curr.next;

                // 如果是头节点，则更新头结点
                if (head == curr) {
                    // 更新头结点
                    head = next;
                } else {
                    // 删除中间节点
                    prev.next = next;
                }

                // 删除节点
                curr.next = null;
                curr = next;
            } else {
                prev = curr;
                curr = curr.next;
            }
        }

        return head;
    }
}
